<template>
	<div>
		<Divider orientation="left">当前在线：</Divider>
		<ul class="userHead">
			<li v-for="item in list" @click="openSocket(item)">
				<Avatar style="background-color: #87d068" icon="ios-person" />
				<span style="margin-left: 5px; font-size: 14px;">{{item.userName}}</span>
			</li>
		</ul>
		<Modal v-model="modal" title="IM" width="500" ok-text="发送" @on-ok="sendMsg">
			<Input v-model="msg" placeholder="Enter something..." />
		</Modal>
	</div>
</template>

<script>
	export default {
		name: "UserIndex",
		data() {
			return {
				list: [],
				modal: false,
				msg: "",
				userInfo: "",
			}
		},
		mounted() {
			this.$sockets.websock.socket.onmessage = this.onWebsocketMessage;
			this.updateOnlines(this.$onlines);
		},
		destroyed() {
			this.$sockets.websock.socket.onmessage = this.$sockets.websocketOnMessage;
		},
		methods: {
			updateOnlines(obj) {
				let arr = obj;
				arr = arr.filter(item => {
					return item.userName
				})
				this.list = arr;
			},
			openSocket(item) {
				console.log(item);
				this.userInfo = item;
				if (!item.id || !item.userName) {
					return;
				}
				if (this.$loginUser.userInfo.accountName !== "root") {
					return;
				}
				this.modal = true;
			},
			sendMsg() {
				const json = {
					type: "IM",
					message: this.msg,
					toUser: this.userInfo,
				};
				this.$sockets.websock.socket.send(JSON.stringify(json));
			},
			onWebsocketMessage(e) {
				if (e.data === "pong") {
					console.log("心跳检测");
				} else if (e.data.indexOf("login") > -1) {
					this.updateOnlines(JSON.parse(e.data));
				} else if (e.data.indexOf("msg:") > -1) {
					this.$Notice.success({
						title: '新消息',
						desc: e.data.split("msg:")[1],
						duration: 0
					});
				} else {
					console.log("接收数据", e.data);
				}
			}
		}
	}
</script>

<style>
	.userHead {
		display: flex;
		justify-content: flex-start;
	}

	.userHead li {
		margin-left: 10px;
	}
</style>
